import React, { useState } from 'react'
import {
    Form,
    Input,
    Button,
    Toast
} from 'antd-mobile'
import "./index.scss"
import { useNavigate } from "react-router-dom"
import { loginInterface } from "../../api/login"
import {useDispatch} from "react-redux"
import {setUserInfo} from "../../store/modules/billStore"

export default function New() {
    let [formData, setFormData] = useState({})
    const dispatch = useDispatch()

    const navigate = useNavigate()
    const loginHandler = async () => {
        console.log('登录', formData)
        if (!formData.username || !formData.password) {
            Toast.show({
                content: '账户密码不能为空',
                afterClose: () => {
                    console.log('after')
                }
            })
            return
        }
        const res = await loginInterface(formData)
        if (res&&res.length!==0) {
            localStorage.setItem('userToken', JSON.stringify(res))
            localStorage.setItem('loginTime',new Date().getTime())
            dispatch(setUserInfo(res))
            navigate('/')
        }else{
            Toast.show({
                content: '用户不存在',
                afterClose: () => {
                    console.log('after')
                }
            })
        }
    }
    const registerUser = () => {
        navigate("/register")
    }

    return <div style={{ display: 'flex', height: '100vh' }} className='loginPage'>
        <div onClick={() => { registerUser() }} style={{ position: 'absolute', top: '10px', right: '10px', color: '#fff', fontSize: '1rem' }}>注册</div>
        <div style={{ margin: 'auto' }}>
            <div style={{ textAlign: 'center', marginBottom: '20px', fontWeight: 'bold', fontSize: '2rem', color: '#fff' }}>登录记账本</div>
            <Form
                layout='vertical'
                footer={
                    <Button block type='submit' color='primary' size='large' onClick={loginHandler}>
                        提交
                    </Button>
                }
            >
                <Form.Item
                    name='name'
                    label='姓名'
                    rules={[{ required: true, message: '姓名不能为空' }]}
                >
                    <Input onChange={(e) => { setFormData({ ...formData, username: e }) }} placeholder='请输入姓名' value={formData.username} />
                </Form.Item>
                <Form.Item
                    name='password'
                    label='密码'
                    rules={[{ required: true, message: '密码不能为空' }]}
                >
                    <Input type='password' onChange={(e) => { setFormData({ ...formData, password: e }) }} placeholder='请输入密码' value={formData.password} />
                </Form.Item>
            </Form>
        </div>
    </div>
}


